﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.IO;
using System.Drawing;
using App2Wpf;
using HandyControl.Controls;
using HandyControl.Data;
using System.Windows.Media.Imaging;
using System.Net;
using System.Net.NetworkInformation;

namespace App2Wpf
{
    class clientFunc
    {

        public static  string logmsg;

        private static string configIPpath = @"IP.config";

        //public static string ConvertToJson(object obj)
        //{
        //    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        //    MemoryStream stream = new MemoryStream();
        //    //null
        //    //无法序列化类型“WindowsFormsApp1.PSCustomObject”。
        //    //请考虑将其标以 DataContractAttribute 特性，并将其所有要序列化的成员标以 DataMemberAttribute 特性。
        //    //如果类型为集合，则请考虑将其标以 CollectionDataContractAttribute 特性。
        //    //有关其他受支持的类型，请参见 Microsoft .NET Framework 文档。
        //    //
        //    serializer.WriteObject(stream, obj);
        //    byte[] dataBytes = new byte[stream.Length];
        //    stream.Position = 0;
        //    stream.Read(dataBytes, 0, (int)stream.Length);
        //    return Encoding.UTF8.GetString(dataBytes);

        //}

        public static string serializeToJson(object obj)
        {
            string jsonString = JsonConvert.SerializeObject(obj);

            return jsonString;

        }

        //public static object JsonToObject(string jsonString, object obj)
        //{
        //    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        //    byte[] middletran = System.Text.Encoding.UTF8.GetBytes(jsonString);
        //    MemoryStream mStream = new MemoryStream(middletran);
        //    return serializer.ReadObject(mStream);

        //}


        public static object JsonToServerObject(string jsonString, object obj)
        {
            ServerInformation remoteServer = new ServerInformation();
            remoteServer = (ServerInformation)JsonConvert.DeserializeObject(jsonString, typeof(ServerInformation));

            return remoteServer;


        }
        public static int GetLocalScreenWidth()
        {
            return (int)System.Windows.SystemParameters.WorkArea.Width;
        }
        public static int GetLocalScreenHeight()
        {
            return (int)System.Windows.SystemParameters.WorkArea.Height;
        }

        


        public static void Showlog(string msg)
        {
            Growl.Info(new GrowlInfo { Message = msg, WaitTime = 2, ShowDateTime = true });
        }
        public static void ShowErrorlog(string msg)
        {
            if(logmsg != msg)
            {
                Growl.Error(new GrowlInfo { Message = msg, WaitTime = 2, ShowDateTime = true });
            }
            
        }




        public static string SHA512Encrypt(string content)
        {
            try
            {
                using (var sha512 = SHA512.Create())
                {
                    byte[] bytevalue = System.Text.Encoding.UTF8.GetBytes(content);

                    var retvalue = sha512.ComputeHash(bytevalue);

                    //return Convert.ToBase64String(retvalue);
                    string res = BitConverter.ToString(retvalue).Replace("-", string.Empty);
                    return res;



                }

            }
            catch (Exception ex)
            {

                throw new Exception();
            }

        }

        public static Bitmap ResizeImage(Bitmap bmp, int width, int height, bool allowEnlarge, bool centerImage, System.Drawing.Color backColor)
        {
            double ratio;
            int newWidth, newHeight;

            if (!allowEnlarge && bmp.Width <= width && bmp.Height <= height)
            {
                ratio = 1.0;
                newWidth = bmp.Width;
                newHeight = bmp.Height;
            }
            else
            {
                double ratioX = (double)width / bmp.Width;
                double ratioY = (double)height / bmp.Height;
                ratio = ratioX < ratioY ? ratioX : ratioY;
                newWidth = (int)(bmp.Width * ratio);
                newHeight = (int)(bmp.Height * ratio);
            }

            int newX = 0;
            int newY = 0;

            if (centerImage)
            {
                newX += (int)((width - (bmp.Width * ratio)) / 2);
                newY += (int)((height - (bmp.Height * ratio)) / 2);
            }

            Bitmap bmpResult = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            bmpResult.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);

            using (Graphics g = Graphics.FromImage(bmpResult))
            {
                if (backColor.A > 0)
                {
                    g.Clear(backColor);
                }

                g.DrawImage(bmp, newX, newY, newWidth, newHeight);
            }

            return bmpResult;
        }


        public static List<nameip> readIP()
        {
            List<nameip> nameips = new List<nameip>();
            File.ReadLines(configIPpath).ToList().ForEach(line =>
            {
                if (line.Contains(","))
                {
                    nameip info = new nameip();
                    info.name = line.Split(',')[0];
                    info.ip = line.Split(',')[1];
                    nameips.Add(info);
                }
            });

            return nameips;
        }

        public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
        {
            BitmapImage bitmapImage = new BitmapImage();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            return bitmapImage;
        }

        public static BitmapImage RenderTargetBitmapToBitmapImage(RenderTargetBitmap rtb)
        {
            var renderTargetBitmap = rtb;
            var bitmapImage = new BitmapImage();
            var bitmapEncoder = new PngBitmapEncoder();
            bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
            using (var stream = new MemoryStream())
            {
                bitmapEncoder.Save(stream);
                stream.Seek(0, SeekOrigin.Begin);
                bitmapImage.BeginInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
            }

            return bitmapImage;
        }


        /// <summary>
        /// Bitmap转byte[]  
        /// </summary>
        /// <param name="Bitmap">Bitmap</param>
        /// <returns></returns>
        public static byte[] BitmapToBytes(Bitmap Bitmap)
        {
            MemoryStream ms = new MemoryStream();
            Bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byteImage = new Byte[ms.Length];
            byteImage = ms.ToArray();
            return byteImage;
        }

        /// <summary>
        /// byte[] 转 BitmapImage
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
            public static BitmapImage BytesToBitmapImage(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                result.StreamSource = ms;
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.EndInit();
                result.Freeze(); ///
                return result;
            }
        }

        public static BitmapImage msToBitmapImage(MemoryStream ms)
        {
            
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                result.StreamSource = ms;
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.EndInit();
                result.Freeze();
                return result;
            
        }

        public unsafe void UpdateWriteableBitmap(byte[] byt, int Width, int Height, WriteableBitmap wbitmap)
        {
            Action DoAction = delegate ()
            {
                try
                {
                    if (wbitmap == null)
                    {
                        wbitmap = new System.Windows.Media.Imaging.WriteableBitmap(
                            Width, Height, 96, 96,
                            System.Windows.Media.PixelFormats.Bgr24,
                            System.Windows.Media.Imaging.BitmapPalettes.Gray256);
                    }
                    wbitmap.Lock();
                    unsafe
                    {
                        if (byt == null)
                        {
                            return;
                        }
                        System.Runtime.InteropServices.Marshal.Copy(byt, 0, wbitmap.BackBuffer, byt.Length);

                    }
                    wbitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, Width, Height)); 
                }
                finally
                {
                    wbitmap.Unlock();
                }
            };
            
        }

        /// <summary>
        /// 获取所有的IP地址
        /// </summary>
        /// <returns>List&lt;Tuple&lt;IP地址名称, IP地址IPAddress&gt;&gt;</returns>
        public static List<Tuple<string, IPAddress>> GetAllIPv4Address()
        {
            var ipList = new List<Tuple<string, IPAddress>>();
            foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (var ua in ni.GetIPProperties().UnicastAddresses)
                {
                    if (ua.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ipList.Add(Tuple.Create(ni.Name, ua.Address));
                    }
                }
            }
            return ipList;
        }

        /// <summary>
        /// 获取所有屏幕信息
        /// <para>当有1个屏幕时，返回1个Tuple</para>
        /// <para>当有n个屏幕时，
        /// 第一个(下标0)是全部屏幕的叠加态，
        /// 第二个(下标1)是主屏幕，
        /// 后面是其他屏幕，
        /// 总共返回n+1个Tuple
        /// </para>
        /// </summary>
        /// <returns>List&lt;Tuple&lt;屏幕名称, 屏幕Rectangle&gt;&gt;</returns>
        public static List<Tuple<string, Rectangle>> GetAllScreen()
        {
            var screenList = new List<Tuple<string, Rectangle>>();
            var screens = System.Windows.Forms.Screen.AllScreens;
            int screenLength = screens.Length;
            if (screenLength == 1)
            {
                screenList.Add(Tuple.Create(screens[0].DeviceName.Remove(0, 11) + "(主)", screens[0].Bounds));
            }
            else
            {
                for (int i = 0; i < screenLength; i++)
                {
                    if (screens[i].Primary)
                    {
                        screenList.Insert(0, Tuple.Create(screens[i].DeviceName.Remove(0, 11) + "(主)", screens[i].Bounds));
                    }
                    else
                    {
                        screenList.Add(Tuple.Create(screens[i].DeviceName.Remove(0, 11), screens[i].Bounds));
                    }
                }
                // 计算全部屏幕的叠加态
                int xMin = screenList.Min(t => t.Item2.Left);
                int yMin = screenList.Min(t => t.Item2.Top);
                int xMax = screenList.Max(t => t.Item2.Right);
                int yMax = screenList.Max(t => t.Item2.Bottom);
                screenList.Insert(0, Tuple.Create("0(全)", new Rectangle(xMin, yMin, xMax - xMin, yMax - yMin)));
            }
            return screenList;
        }


        //private WriteableBitmap PrepareForRendering(VideoBuffer videoBuffer)
        //{
        //    PixelFormat pixelFormat;
        //    if (videoBuffer.pixelFormat == PixelFormats.Rgb24)
        //    {
        //        pixelFormat = PixelFormats.Rgb24;
        //    }
        //    else if (videoBuffer.pixelFormat == PixelFormats.Bgr32)
        //    {
        //        pixelFormat = PixelFormats.Bgra32;
        //    }
        //    else if (videoBuffer.pixelFormat == PixelFormats.Bgr24)
        //    {
        //        pixelFormat = PixelFormats.Bgr24;
        //    }
        //    else
        //    {
        //        throw new Exception("unsupported pixel format");
        //    }
        //    var bitmap = new WriteableBitmap(
        //        videoBuffer.width, videoBuffer.height,
        //        96, 96,
        //        pixelFormat, null
        //    );
        //    //_imgVIew.Source = bitmap;
        //    return bitmap;
        //}






    }
}






    


        
        //public static List<nameip> nameips = new List<nameip>();




        //public static List<T> Range<T>(this List<T> source, int start, int end)
        //{
        //    List<T> list = new List<T>();

        //    if (start > end)
        //    {
        //        for (int i = start; i >= end; i--)
        //        {
        //            list.Add(source[i]);
        //        }
        //    }
        //    else
        //    {
        //        for (int i = start; i <= end; i++)
        //        {
        //            list.Add(source[i]);
        //        }
        //    }

        //    return list;
        //}


        //public static List<T> Range<T>(this List<T> source, T start, T end)
        //{
        //    int startIndex = source.IndexOf(start);
        //    if (startIndex == -1) return new List<T>();

        //    int endIndex = source.IndexOf(end);
        //    if (endIndex == -1) return new List<T>();

        //    return Range(source, startIndex, endIndex);
        //}

